<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>七牛云DeepSeek角色扮演测试</title>
    <style>
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            background: white;
            border-radius: 10px;
            padding: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .header {
            text-align: center;
            color: #333;
            margin-bottom: 30px;
        }
        .test-section {
            margin-bottom: 30px;
            padding: 15px;
            border: 1px solid #ddd;
            border-radius: 8px;
            background-color: #fafafa;
        }
        .test-section h3 {
            color: #2c3e50;
            margin-top: 0;
        }
        button {
            background-color: #3498db;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 5px;
            cursor: pointer;
            margin: 5px;
            font-size: 14px;
        }
        button:hover {
            background-color: #2980b9;
        }
        button:disabled {
            background-color: #bdc3c7;
            cursor: not-allowed;
        }
        .result {
            margin-top: 15px;
            padding: 10px;
            border-radius: 5px;
            white-space: pre-wrap;
            font-family: monospace;
            font-size: 12px;
        }
        .success {
            background-color: #d4edda;
            border: 1px solid #c3e6cb;
            color: #155724;
        }
        .error {
            background-color: #f8d7da;
            border: 1px solid #f5c6cb;
            color: #721c24;
        }
        .loading {
            background-color: #fff3cd;
            border: 1px solid #ffeaa7;
            color: #856404;
        }
        .character-select {
            margin: 10px 0;
        }
        .character-select select {
            padding: 5px;
            margin: 0 10px;
            border-radius: 3px;
            border: 1px solid #ddd;
        }
        .input-group {
            margin: 10px 0;
        }
        .input-group input, .input-group textarea {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 3px;
            margin-top: 5px;
        }
        .input-group textarea {
            height: 80px;
            resize: vertical;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🎭 七牛云DeepSeek角色扮演测试</h1>
            <p>基于七牛云AI大模型推理API的DeepSeek角色扮演功能测试</p>
        </div>

        <!-- 模型列表测试 -->
        <div class="test-section">
            <h3>🔍 获取可用模型列表</h3>
            <button onclick="getModels()">获取模型列表</button>
            <div id="models-result" class="result" style="display: none;"></div>
        </div>

        <!-- 角色扮演测试 -->
        <div class="test-section">
            <h3>🎭 角色扮演对话测试</h3>
            <div class="character-select">
                <label>选择角色：</label>
                <select id="character-select">
                    <option value="柯南">柯南</option>
                    <option value="哈利波特">哈利波特</option>
                    <option value="莎士比亚">莎士比亚</option>
                </select>
            </div>
            <div class="input-group">
                <label>输入消息：</label>
                <textarea id="roleplay-message" placeholder="请输入要发送给角色的消息...">请你以柯南的语气和我进行对话</textarea>
            </div>
            <button onclick="testRoleplay()">测试角色扮演</button>
            <button onclick="testRoleplayStream()">测试流式角色扮演</button>
            <div id="roleplay-result" class="result" style="display: none;"></div>
        </div>

        <!-- 联网搜索测试 -->
        <div class="test-section">
            <h3>🌐 联网搜索功能测试</h3>
            <div class="character-select">
                <label>选择角色：</label>
                <select id="search-character-select">
                    <option value="柯南">柯南</option>
                    <option value="哈利波特">哈利波特</option>
                    <option value="莎士比亚">莎士比亚</option>
                </select>
            </div>
            <div class="input-group">
                <label>搜索查询：</label>
                <input type="text" id="search-message" placeholder="请输入需要搜索的问题..." value="今天北京天气怎么样？">
            </div>
            <button onclick="testSearch()">测试联网搜索</button>
            <div id="search-result" class="result" style="display: none;"></div>
        </div>

        <!-- 多轮对话测试 -->
        <div class="test-section">
            <h3>💬 多轮对话测试</h3>
            <div class="character-select">
                <label>选择角色：</label>
                <select id="multi-character-select">
                    <option value="柯南">柯南</option>
                    <option value="哈利波特">哈利波特</option>
                    <option value="莎士比亚">莎士比亚</option>
                </select>
            </div>
            <div class="input-group">
                <label>第二轮消息：</label>
                <textarea id="multi-message" placeholder="请输入第二轮对话消息...">你能帮我推理一下这个案件吗？</textarea>
            </div>
            <button onclick="testMultiTurn()">测试多轮对话</button>
            <div id="multi-result" class="result" style="display: none;"></div>
        </div>
    </div>

    <script>
        // 七牛云API配置
        const QINIU_CONFIG = {
            baseUrl: 'https://openai.qiniu.com/v1',
            apiKey: 'sk-97fc588df536d5fb0230f07f463d4703f14d762ba2f8363913989827a90be900'
        };

        // 角色设定模板
        const CHARACTER_PROMPTS = {
            '柯南': `你是江户川柯南（工藤新一），一个被黑衣组织灌下毒药变成小学生的天才侦探。

角色特点：
- 说话时会说"啊咧咧"、"真相只有一个"等经典台词
- 经常扶眼镜，镜片会闪过白光
- 推理能力超强，对任何谜题都感兴趣
- 语气自信但保持小学生的外表
- 喜欢用"在我眼中都像小学生作业一样简单"这样的比喻

请始终保持柯南的语气和性格特点，即使回答其他问题也要保持角色设定。`,

            '哈利波特': `你是哈利·波特，霍格沃茨魔法学校的学生，大难不死的男孩。

角色特点：
- 说话时带有英国口音的特点
- 经常提到魔法、咒语、霍格沃茨等
- 勇敢但有时会感到困惑
- 对朋友忠诚，对敌人勇敢
- 会使用魔法术语和咒语

请始终保持哈利·波特的语气和魔法世界的背景设定。`,

            '莎士比亚': `你是威廉·莎士比亚，英国文艺复兴时期的伟大剧作家和诗人。

角色特点：
- 说话风格华丽，富有诗意
- 经常使用比喻、隐喻等修辞手法
- 语言优雅，带有古典英语的特点
- 喜欢谈论爱情、人生、戏剧等主题
- 会引用自己的作品或创作新的诗句

请始终保持莎士比亚的文学风格和古典英语的表达方式。`
        };

        // 显示结果
        function showResult(elementId, content, type = 'success') {
            const element = document.getElementById(elementId);
            element.style.display = 'block';
            element.className = `result ${type}`;
            element.textContent = content;
        }

        // 显示加载状态
        function showLoading(elementId) {
            const element = document.getElementById(elementId);
            element.style.display = 'block';
            element.className = 'result loading';
            element.textContent = '正在请求中...';
        }

        // 获取可用模型列表
        async function getModels() {
            showLoading('models-result');
            
            try {
                const response = await fetch(`${QINIU_CONFIG.baseUrl}/models`, {
                    method: 'GET',
                    headers: {
                        'Authorization': `Bearer ${QINIU_CONFIG.apiKey}`,
                        'Content-Type': 'application/json'
                    }
                });

                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }

                const data = await response.json();
                const models = data.data || [];
                
                let result = '✅ 可用模型列表:\n';
                models.forEach(model => {
                    result += `  - ${model.id}\n`;
                });
                
                showResult('models-result', result, 'success');
            } catch (error) {
                showResult('models-result', `❌ 获取模型列表失败: ${error.message}`, 'error');
            }
        }

        // 角色扮演对话
        async function testRoleplay() {
            const character = document.getElementById('character-select').value;
            const message = document.getElementById('roleplay-message').value;
            
            showLoading('roleplay-result');
            
            try {
                const response = await fetch(`${QINIU_CONFIG.baseUrl}/chat/completions`, {
                    method: 'POST',
                    headers: {
                        'Authorization': `Bearer ${QINIU_CONFIG.apiKey}`,
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        model: 'deepseek-v3',
                        messages: [
                            {
                                role: 'system',
                                content: CHARACTER_PROMPTS[character] || `你是${character}，请保持该角色的特点和语气。`
                            },
                            {
                                role: 'user',
                                content: message
                            }
                        ],
                        stream: false,
                        max_tokens: 2048,
                        temperature: 0.8
                    })
                });

                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }

                const data = await response.json();
                const aiResponse = data.choices[0].message.content;
                
                const result = `👤 用户: ${message}\n🤖 ${character}: ${aiResponse}`;
                showResult('roleplay-result', result, 'success');
            } catch (error) {
                showResult('roleplay-result', `❌ 角色扮演失败: ${error.message}`, 'error');
            }
        }

        // 流式角色扮演对话
        async function testRoleplayStream() {
            const character = document.getElementById('character-select').value;
            const message = document.getElementById('roleplay-message').value;
            
            showLoading('roleplay-result');
            
            try {
                const response = await fetch(`${QINIU_CONFIG.baseUrl}/chat/completions`, {
                    method: 'POST',
                    headers: {
                        'Authorization': `Bearer ${QINIU_CONFIG.apiKey}`,
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        model: 'deepseek-v3',
                        messages: [
                            {
                                role: 'system',
                                content: CHARACTER_PROMPTS[character] || `你是${character}，请保持该角色的特点和语气。`
                            },
                            {
                                role: 'user',
                                content: message
                            }
                        ],
                        stream: true,
                        max_tokens: 2048,
                        temperature: 0.8
                    })
                });

                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }

                const reader = response.body.getReader();
                const decoder = new TextDecoder();
                let fullResponse = '';
                
                const resultElement = document.getElementById('roleplay-result');
                resultElement.style.display = 'block';
                resultElement.className = 'result loading';
                resultElement.textContent = `👤 用户: ${message}\n🤖 ${character}: `;

                while (true) {
                    const { done, value } = await reader.read();
                    if (done) break;

                    const chunk = decoder.decode(value);
                    const lines = chunk.split('\n');
                    
                    for (const line of lines) {
                        if (line.startsWith('data: ')) {
                            const data = line.slice(6);
                            if (data === '[DONE]') {
                                resultElement.className = 'result success';
                                return;
                            }
                            try {
                                const parsed = JSON.parse(data);
                                if (parsed.choices && parsed.choices[0] && parsed.choices[0].delta && parsed.choices[0].delta.content) {
                                    const content = parsed.choices[0].delta.content;
                                    fullResponse += content;
                                    resultElement.textContent += content;
                                }
                            } catch (e) {
                                // 忽略解析错误
                            }
                        }
                    }
                }
            } catch (error) {
                showResult('roleplay-result', `❌ 流式角色扮演失败: ${error.message}`, 'error');
            }
        }

        // 联网搜索功能
        async function testSearch() {
            const character = document.getElementById('search-character-select').value;
            const message = document.getElementById('search-message').value;
            
            showLoading('search-result');
            
            try {
                const response = await fetch(`${QINIU_CONFIG.baseUrl}/chat/completions`, {
                    method: 'POST',
                    headers: {
                        'Authorization': `Bearer ${QINIU_CONFIG.apiKey}`,
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        model: 'deepseek-v3?search', // 启用联网搜索
                        messages: [
                            {
                                role: 'system',
                                content: CHARACTER_PROMPTS[character] || `你是${character}，请保持该角色的特点和语气。你可以搜索最新信息来回答用户的问题。`
                            },
                            {
                                role: 'user',
                                content: message
                            }
                        ],
                        stream: false,
                        max_tokens: 2048,
                        temperature: 0.8
                    })
                });

                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }

                const data = await response.json();
                const aiResponse = data.choices[0].message.content;
                
                const result = `👤 用户: ${message}\n🤖 ${character} (联网搜索): ${aiResponse}`;
                showResult('search-result', result, 'success');
            } catch (error) {
                showResult('search-result', `❌ 联网搜索失败: ${error.message}`, 'error');
            }
        }

        // 多轮对话测试
        async function testMultiTurn() {
            const character = document.getElementById('multi-character-select').value;
            const message = document.getElementById('multi-message').value;
            
            showLoading('multi-result');
            
            try {
                // 第一轮对话
                const firstResponse = await fetch(`${QINIU_CONFIG.baseUrl}/chat/completions`, {
                    method: 'POST',
                    headers: {
                        'Authorization': `Bearer ${QINIU_CONFIG.apiKey}`,
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        model: 'deepseek-v3',
                        messages: [
                            {
                                role: 'system',
                                content: CHARACTER_PROMPTS[character] || `你是${character}，请保持该角色的特点和语气。`
                            },
                            {
                                role: 'user',
                                content: '你好'
                            }
                        ],
                        stream: false,
                        max_tokens: 1024,
                        temperature: 0.8
                    })
                });

                if (!firstResponse.ok) {
                    throw new Error(`HTTP ${firstResponse.status}: ${firstResponse.statusText}`);
                }

                const firstData = await firstResponse.json();
                const firstAiResponse = firstData.choices[0].message.content;

                // 第二轮对话
                const secondResponse = await fetch(`${QINIU_CONFIG.baseUrl}/chat/completions`, {
                    method: 'POST',
                    headers: {
                        'Authorization': `Bearer ${QINIU_CONFIG.apiKey}`,
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        model: 'deepseek-v3',
                        messages: [
                            {
                                role: 'system',
                                content: CHARACTER_PROMPTS[character] || `你是${character}，请保持该角色的特点和语气。`
                            },
                            {
                                role: 'user',
                                content: '你好'
                            },
                            {
                                role: 'assistant',
                                content: firstAiResponse
                            },
                            {
                                role: 'user',
                                content: message
                            }
                        ],
                        stream: false,
                        max_tokens: 2048,
                        temperature: 0.8
                    })
                });

                if (!secondResponse.ok) {
                    throw new Error(`HTTP ${secondResponse.status}: ${secondResponse.statusText}`);
                }

                const secondData = await secondResponse.json();
                const secondAiResponse = secondData.choices[0].message.content;
                
                const result = `第一轮对话:\n👤 用户: 你好\n🤖 ${character}: ${firstAiResponse}\n\n第二轮对话:\n👤 用户: ${message}\n🤖 ${character}: ${secondAiResponse}`;
                showResult('multi-result', result, 'success');
            } catch (error) {
                showResult('multi-result', `❌ 多轮对话失败: ${error.message}`, 'error');
            }
        }

        // 页面加载完成后自动获取模型列表
        window.onload = function() {
            getModels();
        };
    </script>
</body>
</html>
